using Kopernikus.Collections.Generic;
using Kopernikus.Parsing.Utility;

namespace Kopernikus.Parsing.GrammarSets
{
    public class ProductionsByRHS
    {
        private readonly IGrammar m_grammar;
        private SetMap<Symbol, Production> m_rhs;

        public ProductionsByRHS(IGrammar grammar)
        {
            m_grammar = grammar;
        }

        public IGrammar Grammar
        {
            get { return m_grammar; }
        }

        public Set<Production> GetProductionsByRHS(Symbol s)
        {
            if (m_rhs == null)
            {
                m_rhs = new SetMap<Symbol, Production>();

                foreach (Symbol s0 in Grammar.Symbols)
                {
                    m_rhs.MakeSet(s0);
                }

                foreach (Production p in Grammar.Productions)
                {
                    foreach (Symbol rhsSymbol in p.RHS)
                    {
                        m_rhs.MakeSet(rhsSymbol).Add(p);
                    }
                }
            }
            return m_rhs.GetSet(s);
        }
    }
}